/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package olympicgameslogic;

import java.io.*;
import java.util.Collection;
import java.util.Collections;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

/**
 *
 * @author 75
 */
public class DataImporter implements Serializable {

   private String[] columnsNations;
   private String[] fileNameNations;
   private String[] columnsResults;
   private String[] fileNameResults;
   private String[] columnsSports;
   private String[] fileNameSports;
   private String[] columnsEditions;
   private String[] fileNameEditions;

   public DataImporter(String[] columnsNations, String[] columnsResults, String[] columnsSports, String[] columnsEditions) {
      this.columnsNations = columnsNations;
      this.columnsResults = columnsResults;
      this.columnsSports = columnsSports;
      this.columnsEditions = columnsEditions;
   }

   //The default constructor withe the predetermined parameters
   public DataImporter() {
   }

   /**
    * @return the columnsNations
    */
   public String[] getColumnsNations() {
      return columnsNations;
   }

   /**
    * @return the fileNameNations
    */
   public String[] getFileNameNations() {
      return fileNameNations;
   }

   /**
    * @return the columnsResults
    */
   public String[] getColumnsResults() {
      return columnsResults;
   }

   /**
    * @return the fileNameResults
    */
   public String[] getFileNameResults() {
      return fileNameResults;
   }

   /**
    * @return the columnsSports
    */
   public String[] getColumnsSports() {
      return columnsSports;
   }

   /**
    * @return the fileNameSports
    */
   public String[] getFileNameSports() {
      return fileNameSports;
   }

   /**
    * @return the columnsEditions
    */
   public String[] getColumnsEditions() {
      return columnsEditions;
   }

   /**
    * @return the fileNameEditions
    */
   public String[] getFileNameEditions() {
      return fileNameEditions;
   }

   /**
    * @param columnsNations the columnsNations to set
    */
   public void setColumnsNations(String[] columnsNations) {
      this.columnsNations = columnsNations;
   }

   /**
    * @param fileNameNations the fileNameNations to set
    */
   public void setFileNameNations(String[] fileNameNations) {
      this.fileNameNations = fileNameNations;
   }

   /**
    * @param columnsResults the columnsResults to set
    */
   public void setColumnsResults(String[] columnsResults) {
      this.columnsResults = columnsResults;
   }

   /**
    * @param fileNameResults the fileNameResults to set
    */
   public void setFileNameResults(String[] fileNameResults) {
      this.fileNameResults = fileNameResults;
   }

   /**
    * @param columnsSports the columnsSports to set
    */
   public void setColumnsSports(String[] columnsSports) {
      this.columnsSports = columnsSports;
   }

   /**
    * @param fileNameSports the fileNameSports to set
    */
   public void setFileNameSports(String[] fileNameSports) {
      this.fileNameSports = fileNameSports;
   }

   /**
    * @param columnsEditions the columnsEditions to set
    */
   public void setColumnsEditions(String[] columnsEditions) {
      this.columnsEditions = columnsEditions;
   }

   /**
    * @param fileNameEditions the fileNameEditions to set
    */
   public void setFileNameEditions(String[] fileNameEditions) {
      this.fileNameEditions = fileNameEditions;
   }

   public void getNationData(ApplicationData dados, File file) throws InvalidFileException, FileNotFoundException, IOException {
      BufferedReader bufRdr = new BufferedReader(new FileReader(file));
      String line;
      String[] columns = new String[3];
      line = bufRdr.readLine();
      columns = line.split(";");
      String nation = "", code = "", alternateCodes = "";

      if (columns[0].trim().equalsIgnoreCase("code") && columns[1].trim().equalsIgnoreCase("Nation (NOC)")
	      && columns[2].equalsIgnoreCase("Other codes used")) {

	 while ((line = bufRdr.readLine()) != null) {
	    columns = line.split(";");
	    nation = columns[1].trim();
	    code = columns[0].trim();
	    if (dados.getNation(code) == null) {
	       Nation n = new Nation(nation, code);
	       int year;
	       String[] alternatecodes;
	       Edition.GAMESEDITION edition;
	       dados.addNation(n);
	    } else {
//	       System.out.println("Nação " + code + " já configurada!");
	       continue;
	    }

	 }

	 bufRdr.close();

      } else {
	 throw new InvalidFileException("erro");
      }

   }

   public void getSportsData(ApplicationData dados, File file) throws FileNotFoundException, IOException, InvalidFileException {


      BufferedReader bufRdr = new BufferedReader(new FileReader(file));

      String coluna[], line;
      String modality, discipline, disciplineEvent, typeUnit, type, order, men, women, mixed;
      line = bufRdr.readLine();
      coluna = line.split(";");

      if (coluna.length < 7 | !(coluna[0].trim().equalsIgnoreCase("sport") && coluna[1].trim().equalsIgnoreCase("discipline")
	      && coluna[2].trim().equalsIgnoreCase("type") && coluna[3].trim().equalsIgnoreCase("men")
	      && coluna[4].trim().equalsIgnoreCase("women") && coluna[5].trim().equalsIgnoreCase("mixed"))) {
	 throw new InvalidFileException("erro");
      } else {

	 Modality mod;
	 Discipline disc;
	 DisciplineEvent discEv;
	 ClassificationType ct;


	 while ((line = bufRdr.readLine()) != null) {
	    coluna = line.split(";");
	    modality = coluna[0].trim();
	    discipline = coluna[1].trim();
	    type = coluna[2].trim();
	    men = coluna[3].trim();
	    women = coluna[4].trim();
	    mixed = coluna[5].trim();
	    typeUnit = coluna[6].trim();
	    order = coluna[7].trim();


	    mod = dados.getModality(modality);
	    if (mod == null) {
	       mod = new Modality(modality);
	       dados.addModality(mod);
//	    System.out.println("Adicionei a modalidade " + modality);
	    }
	    ct = new ClassificationType();

	    //Defines classification type units and order
	    if (typeUnit.contains(",")) {
	       String units[] = typeUnit.split(",");
	       for (int i = 0; i < units.length; i++) {
		  if (units[i].equalsIgnoreCase("m") || units[i].equalsIgnoreCase("ft")) {
		     ct.setUnit(ClassificationType.MEASUREUNIT.DISTANCE);
		  }
	       }
	    } else if (typeUnit.equalsIgnoreCase("time")) {
	       ct.setUnit(ClassificationType.MEASUREUNIT.TIME);
	    } else if (typeUnit.equalsIgnoreCase("points")) {
	       ct.setUnit(ClassificationType.MEASUREUNIT.POINTS);
	    } else {
	       ct.setUnit(ClassificationType.MEASUREUNIT.RANK);
	    }

	    if (order.equalsIgnoreCase("h")) {
	       ct.setOrder(ClassificationType.ORDER.H);
	    } else {
	       ct.setOrder(ClassificationType.ORDER.L);
	    }

	    // ends classification type definition

	    if (type.equalsIgnoreCase("individual")) {
	       disc = mod.getDiscipline(discipline, Discipline.DISCIPLINETYPE.INDIVIDUAL);
	       if (disc == null) {
		  disc = new Discipline(discipline, mod, ct, Discipline.DISCIPLINETYPE.INDIVIDUAL);
		  mod.addDiscipline(disc);
	       }




	       if (men.equalsIgnoreCase("x")) {
		  disciplineEvent = mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.MEN.toString();
		  discEv = disc.getDisciplineEvent(disciplineEvent, DisciplineEvent.EVENTGENDER.MEN);
		  if (discEv == null) {
		     discEv = new DisciplineEvent(disciplineEvent, disc, DisciplineEvent.EVENTGENDER.MEN);
		     disc.addEvent(discEv);
		  }

	       }
	       if (women.equalsIgnoreCase("x")) {
		  disciplineEvent = mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.WOMEN.toString();
		  discEv = disc.getDisciplineEvent(disciplineEvent, DisciplineEvent.EVENTGENDER.WOMEN);
		  if (discEv == null) {
		     discEv = new DisciplineEvent(disciplineEvent, disc, DisciplineEvent.EVENTGENDER.WOMEN);
		     disc.addEvent(discEv);
		  }
	       }
	       if (mixed.equalsIgnoreCase("x")) {

		  disciplineEvent = mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.MIXED.toString();
		  discEv = disc.getDisciplineEvent(disciplineEvent, DisciplineEvent.EVENTGENDER.MEN);
		  if (discEv == null) {
		     discEv = new DisciplineEvent(disciplineEvent, disc, DisciplineEvent.EVENTGENDER.MIXED);
		     disc.addEvent(discEv);
		  }

	       }


	    } else if (type.equalsIgnoreCase("team")) {
	       disc = mod.getDiscipline(discipline, Discipline.DISCIPLINETYPE.TEAM);
	       if (disc == null) {
		  disc = new Discipline(discipline, mod, ct, Discipline.DISCIPLINETYPE.TEAM);
		  mod.addDiscipline(disc);
	       }



	       if (men.equalsIgnoreCase("x")) {

		  disciplineEvent = mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.MEN.toString();
		  discEv = disc.getDisciplineEvent(disciplineEvent, DisciplineEvent.EVENTGENDER.MEN);
		  if (discEv == null) {
		     discEv = new DisciplineEvent(mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.MEN.toString(), disc, DisciplineEvent.EVENTGENDER.MEN);
		     disc.addEvent(discEv);
		  }
	       }
	       if (women.equalsIgnoreCase("x")) {
		  disciplineEvent = mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.WOMEN.toString();
		  discEv = disc.getDisciplineEvent(disciplineEvent, DisciplineEvent.EVENTGENDER.WOMEN);
		  if (discEv == null) {
		     discEv = new DisciplineEvent(mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.WOMEN.toString(), disc, DisciplineEvent.EVENTGENDER.WOMEN);
		     disc.addEvent(discEv);
		  }
	       }
	       if (mixed.equalsIgnoreCase("x")) {
		  disciplineEvent = mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.MIXED.toString();
		  discEv = disc.getDisciplineEvent(disciplineEvent, DisciplineEvent.EVENTGENDER.MIXED);
		  if (discEv == null) {

		     discEv = new DisciplineEvent(mod.getName() + " / " + disc.getName() + " / " + DisciplineEvent.EVENTGENDER.MIXED.toString(), disc, DisciplineEvent.EVENTGENDER.MIXED);
		     disc.addEvent(discEv);
		  }
	       }

	    }
	 }
      }
      bufRdr.close();

   }

   public void getEditionEventsData(ApplicationData dados, File f) throws FileNotFoundException, IOException, InvalidFileException {
      String fileName = f.getName();


      String filecolumns[];

      filecolumns = fileName.split("\\.");
      fileName = filecolumns[0];
      System.out.println(fileName);

      filecolumns = fileName.split("_");
      if (filecolumns.length < 3) {
	 throw new InvalidFileException("ERROR");
      } else {

	 int readEditionYear = Integer.parseInt(filecolumns[3]);

	 Edition edition = dados.getEdition(readEditionYear);
	 EditionDisciplineEvent edDiscEv;
	 if (edition == null) {
	    edition = new Edition(readEditionYear);
	    dados.addEdition(edition);
	 }

	 BufferedReader bufRdr = new BufferedReader(new FileReader(f));
	 String coluna[], line;

	 line = bufRdr.readLine();
	 coluna = line.split(";");
	 if (!(coluna[0].trim().equalsIgnoreCase("Sport") || coluna[1].trim().equalsIgnoreCase("discipline"))) {
	    throw new InvalidFileException("ERROR");
	 } else {

	    Modality mod;
	    Discipline disc;
	    DisciplineEvent discEv;
	    ClassificationType ct;
	    String modality = "", discipline = "", men = "", women = "", mixed = "";
	    while ((line = bufRdr.readLine()) != null) {
	       coluna = line.split(";");
	       modality = coluna[0].trim();
	       discipline = coluna[1].trim();
	       if (coluna.length > 2) {
		  men = coluna[2].trim();
	       }
	       if (coluna.length > 3) {
		  women = coluna[3].trim();
	       }
	       if (coluna.length > 4) {
		  mixed = coluna[4].trim();
	       }

	       mod = dados.getModality(modality);
	       if (mod == null) {
//	    System.out.println("modalidade " + modality + "not available");
		  continue;
	       } else {
		  disc = mod.getDiscipline(discipline);
		  if (disc == null) {
//	       System.out.println("discipline " + discipline + " of modality " + modality + " not available");
		     continue;
		  } else {

		     if (men.equalsIgnoreCase("x")) {
			discEv = disc.getDisciplineEvent(DisciplineEvent.EVENTGENDER.MEN);
			if (discEv == null) {
//		     System.out.println(modality + discipline + " Man discipline event  not available");
			   continue;
			} else {
			   edDiscEv = edition.getEditionDisciplineEvent(discEv);
			   if (edDiscEv == null) {
			      edDiscEv = new EditionDisciplineEvent(edition, discEv, new LinkedList<EditionEventParticipation>());
			      edition.addEditionDisciplineEvent(edDiscEv);
			   } else {
//			System.out.println(modality + discipline + " Man evento já configurado para essa edição");
			   }

			}
		     }
		     if (women.equalsIgnoreCase("x")) {
			discEv = disc.getDisciplineEvent(DisciplineEvent.EVENTGENDER.WOMEN);
			if (discEv == null) {
//		     System.out.println(modality + discipline + " Women discipline event  not available");
			   continue;
			} else {
			   edDiscEv = edition.getEditionDisciplineEvent(discEv);
			   if (edDiscEv == null) {
			      edDiscEv = new EditionDisciplineEvent(edition, discEv, new LinkedList<EditionEventParticipation>());
			      edition.addEditionDisciplineEvent(edDiscEv);
			   } else {
//			System.out.println(modality + discipline + " Women evento já configurado para essa edição");
			   }
			}
		     }

		     if (mixed.equalsIgnoreCase("x")) {
			discEv = disc.getDisciplineEvent(DisciplineEvent.EVENTGENDER.MIXED);
			if (discEv == null) {
//		     System.out.println(modality + discipline + " Mixed discipline event  not available");
			   continue;
			} else {
			   edDiscEv = edition.getEditionDisciplineEvent(discEv);
			   if (edDiscEv == null) {
			      edDiscEv = new EditionDisciplineEvent(edition, discEv, new LinkedList<EditionEventParticipation>());
			      edition.addEditionDisciplineEvent(edDiscEv);
			   } else {
//			System.out.println(modality + discipline + " Mixed evento já configurado para essa edição");
			   }


			}
		     }

		  }
	       }
	    }
	 }
	 bufRdr.close();
      }

   }

   public void getEditionModalityResults(ApplicationData dados, File file) throws IOException, InvalidFileException {


      String fileName = file.getName();
      StringTokenizer token = new StringTokenizer(fileName, "_");
      if (token.countTokens() != 3) {
	 throw new InvalidFileException("Erro");
      } else {

	 LinkedList<EditionDisciplineEvent> auxEventsList = new LinkedList();
	 LinkedList<EditionDisciplineEvent> aux2 = new LinkedList();
	 Edition edition;
	 Modality modality;
	 Discipline discipline;
	 DisciplineEvent disciplineEvent;
	 Athlete.GENDER atGender = Athlete.GENDER.UNDEF;
	 DisciplineEvent.EVENTGENDER eventGender;
	 BufferedReader bufRdr = new BufferedReader(new FileReader(file));

	 String readLine;

	 int readEditionYear = 0;
	 try{

	  readEditionYear = Integer.parseInt(token.nextToken().trim());
	 }
	 catch (NumberFormatException nfe){
	    throw new InvalidFileException("Erro na leitura");
	 }
	    
	 String readModality = token.nextToken().trim();
	 String readGender = token.nextToken().trim();
	 if (readGender.toUpperCase().contains("WOMEN")) {
	    atGender = Athlete.GENDER.FEMALE;
	    eventGender = DisciplineEvent.EVENTGENDER.WOMEN;
	 } else if (readGender.toUpperCase().contains("MEN")) {
	    eventGender = DisciplineEvent.EVENTGENDER.MEN;
	    atGender = Athlete.GENDER.MALE;
	 } else {
	    eventGender = DisciplineEvent.EVENTGENDER.MIXED;
	    atGender = Athlete.GENDER.UNDEF;
	 }


	 /*
	  * Check if the modality has already been inserted into the system. If
	  * it has the program continues importing In case the modality doesn't
	  * exists it exits and warns the user
	  */
	 modality = dados.getModality(readModality);
	 if (modality == null) {
	 System.out.println("modalidade não configurada no sistema!!!");
	    return;
	 }



	 /*
	  *
	  * At this point we know that the modality really exists in the system
	  * and we can start "drilling" :) down and associating all the data Now
	  * we must go on and start processing the file because we can only get
	  * the gender of the events (we need the type (Individual or Team) and
	  * the discipline and this information is on the data to be imported
	  *
	  */


	 /*
	  * Check if edition already exists and if it doesn't creates it and
	  * adds it to the edition list
	  */

	 if ((edition = dados.getEdition(readEditionYear)) == null) {
	 System.out.println("Edition not yet configured. You must import edition data first");
	    return;
	 }


	 /*
	  * Now lets start reading the file and processing all the data There
	  * will still exist the need for validations for disciplines and
	  * discipline events, and either one can make the import fail in that
	  * specific part
	  *
	  *
	  */
	 /*
	  * We have to define some variables outside of the while cycle
	  *
	  */

	 Discipline.DISCIPLINETYPE type = Discipline.DISCIPLINETYPE.INDIVIDUAL;
	 String readDiscipline = "";

	 String[] columns;
	 
	
	 while ((readLine = bufRdr.readLine()) != null) {
	    columns = readLine.split(";");

	    /*
	     * change mode to individual or team mode that will define the type
	     * of disciplineEvents
	     */

	    if (columns[0].trim().equalsIgnoreCase("individual") && columns[1].trim().isEmpty()) {
	       type = Discipline.DISCIPLINETYPE.INDIVIDUAL;
	    } else if (columns[0].trim().equalsIgnoreCase("team") && columns[1].trim().isEmpty()) {
	       type = Discipline.DISCIPLINETYPE.TEAM;
	    } else if (!columns[1].trim().isEmpty()) {
	       if (!columns[0].trim().isEmpty()) {
		  readDiscipline = columns[0].trim();
	       }
	    }
	    /*
	     * Now me must check if this discipline exists in the modality we
	     * got earlier
	     */

	    System.out.println("li a disciplina:" + readDiscipline + " e estou no tipo:" + type + " " + eventGender);
	    discipline = modality.getDiscipline(readDiscipline.trim(), type);

	    if (discipline == null) {
	       System.out.println("Não existe a disciplina " + readDiscipline + " " + type);
	       continue;
	    } else {

	       //       System.out.println(discipline.getEventsList());

	       /*
	        *
	        * Now that we have the discipline we must go and see if there is
	        * a disciplineEvent of GENDER
	        *
	        */

	       disciplineEvent = discipline.getDisciplineEvent(eventGender);
	       if (disciplineEvent == null) {
		  System.out.println("Não existe o evento " + discipline.getName() + eventGender + " " + type);
		  continue;
	       } else {

		  /*
		   * The discipline event exists and so we must continue
		   * processing the athlete list or team list This is where we
		   * will see if the athlete or team exists and if it doesn't we
		   * must create the correspondig delegation, add it to the
		   * edition we created (got) earlier and add the athlete/team
		   * to it. Then we must insert the event participation
		   */

		  if (type == Discipline.DISCIPLINETYPE.INDIVIDUAL) {
		     EditionDisciplineEvent editionDisciplineEvent = dados.getEdition(readEditionYear).getEditionDisciplineEvent(disciplineEvent);
		     if (editionDisciplineEvent == null) {
			editionDisciplineEvent = new EditionDisciplineEvent(edition, disciplineEvent, new LinkedList<EditionEventParticipation>()); //Cria o evento/edição
			edition.addEditionDisciplineEvent(editionDisciplineEvent);
			//aux2.add(editionDisciplineEvent);
		     }
		     if (!aux2.contains(editionDisciplineEvent)) {
			aux2.add(editionDisciplineEvent);
		     }




		     token = new StringTokenizer(columns[1].trim(), ",");
		     String athleteName = token.nextToken().trim();
		     String country = token.nextToken().trim();
		     Nation nation = dados.getNation(country);
		     if (nation == null) {

			System.out.println("Não existe essa nação configurada no sistema!!!" + country);
			continue;
		     }

		     Delegation delegation = edition.getDelegation(country);
		     if (delegation == null) {
			System.out.println("A delegação de " + nation.getName() + " na edição de " + readEditionYear
				+ " ainda não existe no sistema mas vai ser configurada");
			delegation = new Delegation(nation, edition);
		     }
		     if (!edition.getEditionDelegationList().contains(delegation)) {
			edition.addDelegation(delegation);
		     }
		     Athlete a = dados.getAthlete(athleteName, nation);
		     if (a == null) {
			System.out.println("Atleta n existe por isso vai ser criado e "
				+ "adicionado aos dados da app e a respetiva delegaçao do ano " + readEditionYear);
			a = new Athlete(athleteName, atGender, nation);
			dados.addAthlete(a);
			delegation.addAthlete(a);
		     } else if (!delegation.getAthleteList().contains(a)) {
			delegation.addAthlete(a);
		     }



		     Result result = null;
		     if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.TIME)) {
			//Process result in tiem
			
			TimeResult t = TimeResult.timeParse(columns[2].trim());
			result = new ResultTime(t, ClassificationType.MEASUREUNIT.TIME);

//			
		     } else if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.POINTS)) {
			result = new ResultPoints(Float.parseFloat(columns[2].trim()), ClassificationType.MEASUREUNIT.POINTS);

		     } else if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.DISTANCE)) {
			String distance = columns[2].trim();
			String unidade = "";
			if (distance.toLowerCase().contains("m")) {
			   distance = distance.replaceAll("m", "");
			   unidade = "m";
			}
			if (distance.toLowerCase().contains("ft")) {
			   distance = distance.replaceAll("ft", "");
			   unidade = "ft";
			}
			result = new ResultDistance(Float.parseFloat(distance.trim()), unidade, ClassificationType.MEASUREUNIT.DISTANCE);

		     } else if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.RANK)) {
			result = new ResultRank(Integer.parseInt(columns[2].trim()), ClassificationType.MEASUREUNIT.RANK);
		     }

		     EditionEventAthleteParticipation edEvPart = editionDisciplineEvent.getAthleteParticipation(a);
		     if (edEvPart == null) {
			edEvPart = new EditionEventAthleteParticipation(a, result, editionDisciplineEvent, edition);
			editionDisciplineEvent.addEditionEventParticipation(edEvPart);
		     } else {
			if (!auxEventsList.contains(editionDisciplineEvent)) {
			   auxEventsList.add(editionDisciplineEvent);
			}
			edEvPart.setResult(result);
		     }

		  } else if (type == Discipline.DISCIPLINETYPE.TEAM) {
		     token = new StringTokenizer(columns[1].trim(), "(");
		     String country = token.nextToken().trim();
		     String tm = token.nextToken().trim();
		     tm = tm.replace(")", "");
		     String[] teamMembers = tm.split(",");

		     EditionDisciplineEvent editionDisciplineEvent = dados.getEdition(readEditionYear).getEditionDisciplineEvent(disciplineEvent);

		     if (editionDisciplineEvent == null) {
			editionDisciplineEvent = new EditionDisciplineEvent(edition, disciplineEvent, new LinkedList<EditionEventParticipation>()); //Cria o evento/edição
			edition.addEditionDisciplineEvent(editionDisciplineEvent);
		     }
		     if (!aux2.contains(editionDisciplineEvent)) {
			aux2.add(editionDisciplineEvent);
		     }

		     Nation nation = dados.getNation(country);
		     if (nation == null) {
				System.out.println("TEAM    Não existe essa nação configurada no sistema!!! " + country);
			continue;
		     }

		     Delegation delegation = edition.getDelegation(country);
		     if (delegation == null) {
//			System.out.println("TEAM A delegação de " + nation.getName() + " ainda não existe no sistema mas vai ser configurada");
			delegation = new Delegation(nation, edition);
			edition.addDelegation(delegation);
		     }

		     Team team = new Team(delegation);
		     System.out.println("Team: " + country + " " + disciplineEvent.toString());
		     for (int i = 0; i < teamMembers.length; i++) {
			String athleteName = teamMembers[i].trim();
			Athlete a = dados.getAthlete(athleteName, nation);
			if (a == null) {
			   System.out.println("TEAM Não existia o atleta " + athleteName + " na delegação " + delegation.getCountry().getName());
			   a = new Athlete(athleteName, atGender, nation);
			   dados.addAthlete(a);
			   delegation.addAthlete(a);
			   System.out.println("\n" + teamMembers[i]);
			}

			team.addAthlete2Team(a);
		     }


		     for (Team t : dados.getTeams()) {
			System.out.println("\n a verificxar se team existe");
			if (t.isEqual(team)) {
			   System.out.println("TEAM Já existe a equipa" + team);
			   team = t;
			}
		     }
		     if (!dados.getTeams().contains(team)) {

			dados.addTeam(team);
		     }
		     if (!delegation.getTeamList().contains(team)) {
			System.out.println("\nTESTE2\n");
			delegation.addTeam(team);
		     }


		     Result result = null;
		     if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.TIME)) {
			olympicgameslogic.TimeResult t = TimeResult.timeParse(columns[2].trim());
			System.out.println(t);
			result = new ResultTime(t, ClassificationType.MEASUREUNIT.TIME);
		     } else if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.POINTS)) {
			result = new ResultPoints(Float.parseFloat(columns[2].trim()), ClassificationType.MEASUREUNIT.POINTS);

		     } else if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.DISTANCE)) {
			String distance = columns[2].trim();
			String unidade = "";
			if (distance.toLowerCase().contains("m")) {
			   distance = distance.replaceAll("m", "");
			   unidade = "m";
			}
			if (distance.toLowerCase().contains("ft")) {
			   distance = distance.replaceAll("ft", "");
			   unidade = "ft";
			}

			result = new ResultDistance(Float.parseFloat(distance.trim()), unidade, ClassificationType.MEASUREUNIT.DISTANCE);

		     } else if (discipline.getcType().getUnit().equals(ClassificationType.MEASUREUNIT.RANK)) {
			result = new ResultRank(Integer.parseInt(columns[2].trim()), ClassificationType.MEASUREUNIT.RANK);
		     }
		     EditionEventTeamParticipation edEvPart = editionDisciplineEvent.getTeamParticipation(team);
		     if (edEvPart == null) {
			edEvPart = new EditionEventTeamParticipation(team, result, editionDisciplineEvent, edition);
			editionDisciplineEvent.addEditionEventParticipation(edEvPart);
		     } else {

			if (!auxEventsList.contains(editionDisciplineEvent)) {
			   auxEventsList.add(editionDisciplineEvent);
			}
			System.out.println("TEAM Já existe a participação. vou so fazer update ao resultado");
			edEvPart.setResult(result);

		     }
		  }
	       }
	    }
	 }
	 bufRdr.close();

	 System.out.println("Provas a fazer reset:" + auxEventsList.size());
	 for (EditionDisciplineEvent aux : auxEventsList) {

	    // System.out.println("\n--------------------------------\n " + aux.toString() + "\n------------------");
	    dados.resetMedals(aux);
	 }
	 System.out.println("provas a atrubuir medalhas a seguir:" + aux2.size());
	 for (EditionDisciplineEvent ed : aux2) {
	    ed.assignMedals();


	 }
      }

   }

   public LinkedList<AppUser> importUsers() throws ClassNotFoundException {
      LinkedList<AppUser> userList = null;
      try {
	 ObjectInputStream in = new ObjectInputStream(new FileInputStream("userdata.bin"));
	 userList = (LinkedList<AppUser>) in.readObject();
	 in.close();
      } catch (IOException ex) {
	 JOptionPane.showMessageDialog(null, ex.getMessage(), "Reposição do Estado", JOptionPane.ERROR_MESSAGE);
      }

      return userList;
   }
}
